#!/usr/bin/env python
# encoding: utf-8

from app.views.webapi import route_api
from  flask import request,jsonify,g
import requests,json,decimal

from app import db
from app.model import User
from app.model import Electronic
from app.model import ElectronicOrder
from app.model import ElectronicOrderLog
from app.model import ElectronicOrderItem

from app.common.libs.Helper import getFormatDate, getCurrentDate
from app.common.libs.electronic.OrderService import OrderService
from app.common.libs.UserService import UserService
from app.common.libs.ElectronicService import ElectronicService
from sqlalchemy import func, desc, or_

# import pysnooper

@route_api.route("/electronicOrder/create",methods = [ "GET","POST" ])
def electronicOrderCreate():
    resp = { 'code':20000,'message':'创建成功~', 'data':{}}
    try:
        data = json.loads(request.get_data())
        order_model = ElectronicOrder()
        order_model.type = data['type']
        order_model.count = data['count']
        order_model.project = data['project']
        order_model.note = data['note']
        order_model.sn = OrderService.geneSn()
        order_model.status = 1
        order_model.created_time = order_model.updated_time = getCurrentDate()
        user_info = UserService.getUserInfo(request)
        order_model.user_id = user_info.id
        db.session.add( order_model )
        db.session.commit()
        # 创建订单所需元器件
        ids = data['electronic_ids']
        cnts = data['electronic_cnts']
        for id_, cnt in zip(ids, cnts):
            order_item_model = ElectronicOrderItem()
            order_item_model.electronic_order_id = order_model.id
            order_item_model.electronic_id = id_
            order_item_model.count = cnt
            db.session.add( order_item_model )
        # 添加操作日志
        order_log_model = ElectronicOrderLog()
        order_log_model.electronic_order_id = order_model.id
        order_log_model.created_time = getCurrentDate()
        order_log_model.status = 1
        order_log_model.log = '创建订单'
        order_log_model.user_id = user_info.id
        db.session.add(order_log_model)
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        resp['code'] = -1
        resp['message'] = "下单失败请重新下单"
        return jsonify( resp )

    return jsonify( resp )

@route_api.route("/electronicOrder/fetch",methods = [ "GET","POST" ])
def electronicOrderFetch():
    resp = { 'code':20000,'message':'查询成功~', 'data':{}}
    req = request.values
    page = int( req['page'] ) if 'page' in req else 0
    limit = int( req['limit'] ) if 'limit' in req else 0
    offset = ( page - 1 ) * limit
    total = 0

    sn = req['sn'] if 'sn' in req else ''
    type = req['type'] if 'type' in req else 0
    status = req['status'] if 'status' in req else 0

    user_info = UserService.getUserInfo(request)
    query = ''
    if user_info.roles == '财务':
        resp = OrderService.financeFetch(request)
        return jsonify( resp )
    if user_info.roles == '库管':
        query = '''
                select o.id, o.sn, o.status, o.type, o.project, o.note, o.created_time, u.nickname
                from `user` as u, `electronic_order` as o
                where (o.type=1 or o.type=2) and o.user_id=u.id
                '''
    if user_info.roles == '研发':
        query = '''
                select o.id, o.sn, o.status, o.type, o.project, o.note, o.created_time, u.nickname
                from `user` as u, `electronic_order` as o
                where o.user_id=u.id and u.id=%s
                '''%user_info.id
    if user_info.roles == '采购':
        query = '''
                select o.id, o.sn, o.status, o.type, o.project, o.note, o.created_time, u.nickname
                from `user` as u, `electronic_order` as o
                where (o.type=1 or o.type=3) and o.user_id=u.id
                '''
    if user_info.roles == 'admin':
        query = '''
                select o.id, o.sn, o.status, o.type, o.project, o.note, o.created_time, u.nickname
                from `user` as u, `electronic_order` as o
                where o.user_id=u.id
                '''
    if sn:
        query += ' and o.sn=%s'%req['sn']
    if type:
        query += ' and o.type=%s'%req['type']
    if status:
        query += ' and o.status=%s'%req['status']

    # 按时间最近排序，分页展示
    query += ' order by o.created_time desc limit %s, %s'%(offset, limit)
    order_list = db.session.execute(query)

    items = []
    for order in order_list:
        total += 1 # 订单总数加1
        items.append( {
            'id':           order[0],
            'sn':           order[1],
            'status':       order[2],
            'type':         order[3],
            'project':      order[4],
            'note':         order[5],
            'created_time': getFormatDate(order[6]),
            'user':         order[7],
        } )


    resp['data']['items'] = items
    resp['data']['total'] = total

    return jsonify( resp )

# 订单条目
@route_api.route("/electronicOrderItem/fetch",methods = [ "GET","POST" ])
def electronicOrderItemFetch():
    resp = { 'code':20000,'message':'创建成功~', 'data':{}}
    req = request.values
    page = int( req['page'] ) if 'page' in req else 0
    limit = int( req['limit'] ) if 'limit' in req else 0
    offset = ( page - 1 ) * limit

    user_info = UserService.getUserInfo(request)
    query = db.session.query( ElectronicOrder, User)\
            .filter(ElectronicOrder.user_id == User.id)\
            .filter(or_(ElectronicOrder.type==1, ElectronicOrder.type==2))

    if 'sn' in req:
        sn = req['sn']
        if sn:
            query = query.filter(ElectronicOrder.sn.like('%'+sn+'%'))
    if 'status' in req:
        if req['status']:
            status = int( req['status'] )
            query = query.filter(ElectronicOrder.status == status)
    if 'type' in req:
        if req['type']:
            type = int( req['type'] )
            query = query.filter(ElectronicOrder.type == type)

    total = query.count()
    order_list = query.order_by(desc(ElectronicOrder.created_time)).offset( offset ).limit( limit ).all()

    orders = []
    for order, user in order_list:
        order_items = ElectronicOrderItem.query.filter_by(electronic_order_id = item.id).all()
        items = [{
            'item_id': item.id,
            'item_count': item.count,
            'electronic_id': electronic.id,
            'electronic_sn': electronic.sn,
            'electronic_name': electronic.name,
            'electronic_position': electronic.position,
            'electronic_package': electronic.package,
            'electronic_spec': electronic.spec,
            'electronic_price': str(electronic.price),
            'electronic_stock': electronic.stock,
            'electronic_supplier': electronic.supplier,
        } for item in order_items ]

        orders.append({
            'id':order.id,
            'sn':order.sn,
            'status':order.status,
            'type':order.type,
            'created_time':getFormatDate(order.created_time),
            'user': user.nickname,
            'items': items
        })
    print(orders)

    resp['data']['items'] = orders
    resp['data']['total'] = total

    return jsonify( resp )

@route_api.route("/electronicOrder/delete/<int:id>",methods = [ "GET","POST" ])
def electronicOrderDelete(id):
    resp = { 'code':20000,'message':'删除成功~', 'data':{}}
    order = ElectronicOrder.query.filter_by(id = id).first()
    if not order:
        resp['code'] = -1
        resp['message'] = '订单不存在'
        return jsonify( resp )
    # 删除订单
    db.session.delete(order)
    # 删除订单下的item
    order_items = ElectronicOrderItem.query.filter_by(electronic_order_id = id).all()
    for item in order_items:
        db.session.delete(item)
    # 删除订单下的操作日志
    order_log = ElectronicOrderLog.query.filter_by(electronic_order_id = id).all()
    for log in order_log:
        db.session.delete(log)
    db.session.commit()
    return jsonify( resp )

@route_api.route("/electronicOrder/detail/<int:id>",methods = [ "GET","POST" ])
def electronicOrderDetail(id):
    resp = { 'code':20000,'message':'创建成功~', 'data':{}}
    electronic_order_items = db.session.query( Electronic, ElectronicOrderItem)\
        .filter(ElectronicOrderItem.electronic_id == Electronic.id)\
        .filter(ElectronicOrderItem.electronic_order_id == id)\
        .all()
    electronicList = []
    totalAmount = 0
    for electronic, item in electronic_order_items:
        if electronic.price:
            price = float(electronic.price)
            amount = int(item.count) * float(electronic.price)
        else:
            amount = 0
            price = 0

        totalAmount += amount

        electronicList.append({
            'electronic_id': electronic.id,
            'sn': electronic.sn,
            'name': electronic.name,
            'position': electronic.position,
            'package': electronic.package,
            'spec': electronic.spec,
            'price': price,
            'stock': electronic.stock,
            'supplier': electronic.supplier,
            'item_id': item.id,
            'count': item.count,
            'amount': amount
        })
    # 获取订单详情
    user_info = UserService.getUserInfo(request)
    info = db.session.query( ElectronicOrder, User )\
                .filter(ElectronicOrder.user_id == User.id)\
                .filter(ElectronicOrder.id == id)\
                .first()
    order_info = info[0]
    user_info = info[1]
    order = {
        'id':order_info.id,
        'sn':order_info.sn,
        'status':order_info.status,
        'type':order_info.type,
        'project':order_info.project,
        'note':order_info.note,
        'created_time':getFormatDate(order_info.created_time),
        'totalAmount':totalAmount
    }
    # 订单提交人信息
    user = {
        'id':user_info.id,
        'nickname':user_info.nickname,
        'mobile':user_info.mobile
    }
    # 获取订单操作记录
    log_info = db.session.query( ElectronicOrderLog, User)\
                .filter(ElectronicOrderLog.electronic_order_id == id)\
                .filter(ElectronicOrderLog.user_id == User.id)\
                .all()
    logList = [{
        'user': user.nickname,
        'log': log.log,
        'status': log.status,
        'created_time': getFormatDate(log.created_time)
    } for log, user in log_info]

    resp['data']['order'] = order
    resp['data']['user'] = user
    resp['data']['electronicList'] = electronicList
    resp['data']['logList'] = logList

    return jsonify( resp )

# 订单修改
@route_api.route("/electronicOrderItem/update",methods = [ "GET","POST" ])
def electronicOrderItemUpdate():
    resp = { 'code':20000,'message':'修改成功~', 'data':{}}
    req = request.values

    electronic_id = int( req['electronic_id'] ) if 'electronic_id' in req else 0
    electronic = Electronic.query.filter_by(id=electronic_id).first()

    # 修改订单内容时重新生成新的产品
    electronic_model              = Electronic()
    electronic_model.name         = electronic.name
    electronic_model.sn           = ElectronicService.geneSn()
    electronic_model.package      = electronic.package
    if 'electronic_price' in req:
        price = float( req['electronic_price'] )
        electronic_model.price = decimal.Decimal( price )
    electronic_model.spec         = electronic.spec
    electronic_model.stock        = 0
    electronic_model.position     = electronic.position
    electronic_model.status       = 1
    electronic_model.supplier     = electronic.supplier
    electronic_model.delivery     = electronic.delivery
    electronic_model.project      = electronic.project
    electronic_model.updated_time = electronic_model.created_time = getCurrentDate()

    db.session.add( electronic_model )
    db.session.commit()

    # 更新订单条目绑定的元器件id为新添加的元器件id
    order_item_id = int( req['order_item_id'] ) if 'order_item_id' in req else 0

    item = ElectronicOrderItem.query.filter_by(id=order_item_id).first()
    item.electronic_id = electronic_model.id

    db.session.commit()
    return jsonify( resp )

@route_api.route("/electronicOrder/outstock",methods = [ "GET","POST" ])
def electronicOrderOutstock():
    resp = { 'code':20000,'message':'出库完成~', 'data':{}}
    req = request.values
    id = int(req['id']) if 'id' in req else 0

    order = ElectronicOrder.query.filter_by(id = id).first()
    if not order:
        resp['code'] = -1
        resp['message'] = '订单不存在'
        return jsonify( resp )
    # 出库元器件
    order_items = db.session.query(ElectronicOrderItem, Electronic)\
        .filter(ElectronicOrderItem.electronic_order_id == id)\
        .filter(ElectronicOrderItem.electronic_id == Electronic.id)\
        .all()
    items = [{
        'electronic_name':electronic.name,
        'electronic_id':item.electronic_id,
        'count':item.count
    } for item, electronic in order_items]
    resp = OrderService.outStock(items=items)
    # 修改订单状态
    order.status = 3
    # 添加操作记录
    content = req['content'] if 'content' in req else ''
    order_log = ElectronicOrderLog()
    order_log.status = 3
    order_log.log = content
    order_log.created_time = getCurrentDate()
    order_log.electronic_order_id = order.id
    user_info = UserService.getUserInfo(request)
    order_log.user_id = user_info.id

    db.session.add(order_log)
    db.session.commit()
    return jsonify( resp )

# 订单状态变化记录
@route_api.route("/electronicOrder/changeStatus",methods = [ "GET","POST" ])
def electronicOrderChangeStatus():
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}
    req = request.values
    user_info = UserService.getUserInfo(request)
    id = int(req['id']) if 'id' in req else 0
    type = int(req['type']) if 'type' in req else 0
    status = int(req['status']) if 'status' in req else 0
    content = req['content'] if 'content' in req else ''
    order = ElectronicOrder.query.filter_by(id = id).first()
    order.checker_id = user_info.id
    if not order:
        resp['code'] = -1
        resp['message'] = '订单不存在'
        return jsonify( resp )
    if type==1 and status == 3: # 入库订单
        resp = OrderService.inStock(order_id=id)
        pass
    if type==2 and status == 3: # 出库订单
        # 出库元器件
        receiver_id = int(req['receiver_id']) if 'receiver_id' in req else 0
        order_items = db.session.query(ElectronicOrderItem, Electronic)\
            .filter(ElectronicOrderItem.electronic_order_id == id)\
            .filter(ElectronicOrderItem.electronic_id == Electronic.id)\
            .all()
        items = [{
            'electronic_name':electronic.name,
            'electronic_id':item.electronic_id,
            'receiver_id':receiver_id,
            'operater_id':user_info.id,
            'count':item.count
        } for item, electronic in order_items]
        resp = OrderService.outStock(items=items)

    # 修改订单状态
    order.status = status
    # 添加操作记录
    order_log = ElectronicOrderLog()
    order_log.status = status
    order_log.log = content
    order_log.created_time = getCurrentDate()
    order_log.electronic_order_id = order.id
    order_log.user_id = user_info.id
    db.session.add(order_log)
    db.session.commit()

    return jsonify( resp )


# 订单统计功能
@route_api.route("/electronicOrder/statistics",methods = [ "GET","POST" ])
# @pysnooper.snoop()
def electronicOrderStatistics():
    resp = { 'code':20000,'message':'出库完成~', 'data':{}}

    # 已经处理订单

    #  query_1 = query.filter(ElectronicOrder.type==1)
    #  query_2 = query.filter(ElectronicOrder.type==2)
    #  query_3 = query.filter(ElectronicOrder.type==3)

    # 各类订单数量
    query = db.session.query(ElectronicOrder)\
            .filter(ElectronicOrder.status == 3)
    total_order= query.count()
    total_instock_order= query.filter(ElectronicOrder.type==1).count()
    total_outstock_order= query.filter(ElectronicOrder.type==2).count()
    total_purchase_order= query.filter(ElectronicOrder.type==3).count()

    # 元器件总费用统计
    query = db.session.query(func.sum(ElectronicOrderItem.count*Electronic.price))\
        .filter(ElectronicOrderItem.electronic_order_id == ElectronicOrder.id)\
        .filter(ElectronicOrderItem.electronic_id == Electronic.id)\
        .filter(ElectronicOrder.status == 3)
    total_instock_price = query.filter(ElectronicOrder.type==1).first()
    total_outstock_price = query.filter(ElectronicOrder.type==2).first()
    total_purchase_price = query.filter(ElectronicOrder.type==3).first()
    # 元器件数量
    query = db.session.query(func.sum(ElectronicOrderItem.count))\
        .filter(ElectronicOrderItem.electronic_order_id == ElectronicOrder.id)\
        .filter(ElectronicOrder.status == 3)

    total_instock_electronic = query.filter(ElectronicOrder.type==1).first()
    total_outstock_electronic = query.filter(ElectronicOrder.type==2).first()
    total_purchase_electronic = query.filter(ElectronicOrder.type==3).first()

    resp['data'] = {
        'total_order':total_order,
        'total_instock_order':total_instock_order,
        'total_outstock_order':total_outstock_order,
        'total_purchase_order':total_purchase_order,
        'total_instock_price':float(total_instock_price[0]),
        'total_outstock_price':float(total_outstock_price[0]),
        'total_purchase_price':float(total_purchase_price[0]),
        'total_instock_electronic':int(total_instock_electronic[0]),
        'total_outstock_electronic':int(total_outstock_electronic[0]),
        'total_purchase_electronic':int(total_purchase_electronic[0])
    }

    return jsonify( resp )

